package com.famiover.generator.generator;

import com.famiover.generator.utils.Utils;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.internal.DefaultCommentGenerator;

import java.util.Date;


public class CustomCommentGenerator extends DefaultCommentGenerator {

    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {

        //1. Swagger处理
        Context context = introspectedColumn.getContext();
        String enableSwagger = Utils.getPropertyDefault(context, "Swagger", "false");
        if (Utils.isTrue(enableSwagger)) {
            String remarks = introspectedColumn.getRemarks();
            if (Utils.isNotEmpty(remarks)) {
                String swagger = "@ApiModelProperty(\"%s\")";
                field.addJavaDocLine(String.format(swagger, remarks));
            }
        } else {
            if (introspectedColumn.getRemarks() != null && introspectedColumn.getRemarks().trim().length() > 0) {
                field.addJavaDocLine("// " + introspectedColumn.getRemarks());
            }
        }

        // 2. 日期处理
        String jsonDate = Utils.getPropertyDefault(context, "JsonDate", "false");
        if (Utils.isTrue(jsonDate)) {
            FullyQualifiedJavaType type = field.getType();
            FullyQualifiedJavaType dateJavaType = new FullyQualifiedJavaType(Date.class.getName());
            if (type.equals(dateJavaType)) {
                String dateFormat = "@JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")";
                field.addJavaDocLine(dateFormat);
            }
        }
    }

    @Override
    public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        Context context = introspectedTable.getContext();
        String swagger = Utils.getPropertyDefault(context, "Swagger", "false");
        String jsonDate = Utils.getPropertyDefault(context, "JsonDate", "false");
        if (Utils.isTrue(swagger)) {
            String remarks = introspectedTable.getRemarks();
            if (Utils.isNotEmpty(remarks)) {
                String format = String.format("@ApiModel(\"%s\")", remarks);
                Utils.modelAddAnnotation(topLevelClass, "io.swagger.annotations.ApiModel", format);
            }
            topLevelClass.addImportedType("io.swagger.annotations.ApiModelProperty");
        }
        if (Utils.isTrue(jsonDate)) {
            topLevelClass.addImportedType("com.fasterxml.jackson.annotation.JsonFormat");
        }
    }
}
